package net.bblbs.zhongrx;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;


import com.bumptech.glide.Glide;

import net.bblbs.zhongrx.util.AttachEnum;
import net.bblbs.zhongrx.util.FileStoreUtil;
import net.bblbs.zhongrx.util.ImageUTIL;
import net.bblbs.zhongrx.util.StringUtil;
import net.bblbs.zhongrx.view.MyImageView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;


public class DynamicPhotoFragment extends Fragment implements View.OnClickListener{
    private static final String TAG = "ZRX_DYNAMIC_PHOTO";
    public static final String SP_NAME = "dynamic_photo";

    private ArrayList<String> mCurrImgList = new ArrayList<String>();
    private ArrayList<String> mPrevImgList = new ArrayList<String>();

    String personId;
    SectionListActivity  parent;

    FloatingActionButton addIV = null;
    LinearLayout ll = null;

    public MyImageView mCurrentMyImageView=null;
    public int mCurrentIndex = -1;

    public DynamicPhotoFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "进入页面初始化");
        View view = inflater.inflate(R.layout.dynamic_photo_fragment, container, false);


        parent = (SectionListActivity) getActivity();
        personId = parent.person.getId();

        ll= (LinearLayout) view.findViewById(R.id.ll_photo);

        addIV = (FloatingActionButton) view.findViewById(R.id.add_photo);
        addIV.setOnClickListener(this);

        mPrevImgList = parent.mDynImgList;

        bindViews(view);
        return view;
    }

    private void bindViews(View view) {
        SharedPreferences pref = parent.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);

        String names = pref.getString(SP_NAME + "_" + personId,"");
        String[] nameArray = names.split("\\|", -1);

        if (nameArray.length ==1 && nameArray[0].trim().equals("")) {
            return;
        }
        for(int i  = 0; i < mPrevImgList.size() ; i++){
            mCurrImgList.add("");
        }

        for (int i =0; i < nameArray.length; i ++) {

            MyImageView newIV = new MyImageView(parent);
            newIV.setFragment(this);
            newIV.setIndex(i);
            newIV.setBackgroundResource(R.drawable.id_photo);
            newIV.setLayoutParams(new LinearLayout.LayoutParams(550,400));
            newIV.setScaleType(ImageView.ScaleType.FIT_XY);
            ll.addView(newIV);

            if (!TextUtils.isEmpty(mPrevImgList.get(i))) {
                Glide.with(parent).load(mPrevImgList.get(i)).into(newIV);
            }

            Button imageButton = new Button(parent);
            imageButton.setText(nameArray[i]);
            imageButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            imageButton.setOnClickListener(this);
            ll.addView(imageButton);


//            if (entry.getKey().equals(buttonName)){
//                dispatchTakePictureIntent((Integer)entry.getValue());
//                exists = true;
//            }
        }


    }

    @Override
    public void onClick(View v) {

        if (v instanceof Button) {
            mCurrentMyImageView = (MyImageView) ll.getChildAt(ll.indexOfChild(v) -1);
            dispatchTakePictureIntent(((Button) v).getText().toString());
        }
        switch (v.getId()) {
            case R.id.add_photo:

                AlertDialog.Builder alert = new AlertDialog.Builder(parent);
                final EditText edittext = new EditText(parent);
                alert.setTitle("添加照片");
                alert.setMessage("请输入照片名称");


                alert.setView(edittext);
                alert.setPositiveButton("确定", null);
                alert.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // what ever you want to do with No option.
                    }
                });

                final AlertDialog alertDialog = alert.create();
                alertDialog.show();
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final String imageName = edittext.getText().toString().trim();

                        if (TextUtils.isEmpty(imageName)) {
                            Toast.makeText(parent, "请输入图片名称", Toast.LENGTH_SHORT).show();
                            return;
                        }

//                        if (nameExitsInEnum(imageName)){
//                            Toast.makeText(parent, "图片名称重复", Toast.LENGTH_SHORT).show();
//                            return;
//                        }

                        SharedPreferences pref = parent.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
                        String names = pref.getString(SP_NAME + "_" + personId,"");


                        if(StringUtil.getIndexOfArray(names, imageName)>-1){
                            Toast.makeText(parent, "图片名称重复", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        String newNames= "";
                        if(names.equals("")){
                            newNames =imageName;
                        }else{
                            newNames = names +"|" + imageName;
                        }

                        SharedPreferences.Editor editor = pref.edit();
                        editor.putString(SP_NAME + "_" + personId, newNames);
                        editor.apply();

                        MyImageView newIV = new MyImageView(parent);
                        newIV.setFragment(DynamicPhotoFragment.this);
                        newIV.setBackgroundResource(R.drawable.id_photo);
                        newIV.setLayoutParams(new LinearLayout.LayoutParams(550,400));
                        newIV.setScaleType(ImageView.ScaleType.FIT_XY);
                        ll.addView(newIV);


                        Button imageButton = new Button(parent);
                        imageButton.setText(imageName);
                        imageButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                        imageButton.setOnClickListener(DynamicPhotoFragment.this);
                        ll.addView(imageButton);



                        mCurrImgList.add("");
                        mPrevImgList.add("");

                        alertDialog.dismiss();
                    }
                });

                break;
            default:
                break;
        }
    }

    private void dispatchTakePictureIntent(String buttonName) {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        SharedPreferences pref = parent.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        String names = pref.getString(SP_NAME+ "_" + personId,"");
        int index = StringUtil.getIndexOfArray(names, buttonName);
        if (index ==-1) {
            return;
        }

        mCurrentIndex = index;

        File imageFile = null;
        try {
            imageFile = FileStoreUtil.setUpPhotoFile(personId,SP_NAME + "_" + index,parent);
            mCurrImgList.set(index ,imageFile.getAbsolutePath());
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
        } catch (IOException e) {
            Log.e(TAG, "dispatchTakePictureIntent: DISTRICT_IMG: "+ e.toString() );
            imageFile = null;
        }


        startActivityForResult(takePictureIntent, 1);
    }

//    public boolean nameExitsInEnum(String name){
//        for(AttachEnum a : AttachEnum.values()) {
//            String enumName = a.getValue();
//            if (enumName.contains("照片") && name.equals(enumName.substring(0, enumName.indexOf("照片")))) {
//                return true;
//            }
//        }
//        return false;
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if (requestCode ==2){
            if (resultCode == Activity.RESULT_OK ) {
                try {
                    File tmpFile = null;
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(ZRXApplication.getAppContext().getContentResolver(), intent.getData());
                    tmpFile = FileStoreUtil.setUpPhotoFile(personId, SP_NAME+ "_" + mCurrentIndex, parent);
                    ImageUTIL.compressImg(bitmap, tmpFile.getAbsolutePath());
                    mCurrImgList.set(mCurrentIndex ,tmpFile.getAbsolutePath());

                    FileStoreUtil.deleteOldFile(mPrevImgList.get(mCurrentIndex));
                    Glide.with(parent).load(mCurrImgList.get(mCurrentIndex)).into(mCurrentMyImageView);
                    mPrevImgList.set(mCurrentIndex, mCurrImgList.get(mCurrentIndex));


                }catch(IOException e){
                    Log.d(TAG, "onActivityResult: "+ e.toString());
                }


            }

        }else if (requestCode ==1){
            if (resultCode == Activity.RESULT_OK ) {

                FileStoreUtil.deleteOldFile(mPrevImgList.get(mCurrentIndex));
                ImageUTIL.compressImg(mCurrImgList.get(mCurrentIndex));
                Glide.with(parent).load(mCurrImgList.get(mCurrentIndex)).into(mCurrentMyImageView);
                mPrevImgList.set(mCurrentIndex, mCurrImgList.get(mCurrentIndex));

            }

            if (resultCode == Activity.RESULT_CANCELED){
                if (mCurrImgList.get(mCurrentIndex) !=null){
                    File file = new File(mCurrImgList.get(mCurrentIndex));
                    file.delete();
                }
            }
        }



    }

}